package com.zhang.modules.file.service.impl;

import com.zhang.common.jpa.entity.DTO;
import com.zhang.common.jpa.service.impl.BaseServiceImpl;
import com.zhang.modules.file.entity.CosFileInfo;
import com.zhang.modules.file.entity.cmd.FileNamePageCmd;
import com.zhang.modules.file.entity.dto.CosFileInfoDto;
import com.zhang.modules.file.rep.CosFileRep;
import com.zhang.modules.file.service.ICosFileService;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * cos本地信息
 */
@Service
public class CosFileService extends BaseServiceImpl<CosFileRep, CosFileInfo,String> implements ICosFileService {




    /**
     * 根据名称和bucketName判断是否已经上传
     */
    @Override
    public CosFileInfo save(CosFileInfo entity) {
        CosFileInfo fileInfo = getRep().isExists(entity.getBucketName() , entity.getObjectKey());
        if (fileInfo == null) return super.save(entity);
        else return fileInfo;
    }


    /**
     * @return true 该文件已经上传过了 false 文件还未上传
     */
    @Override
    public Boolean isExists(CosFileInfo entity) {
        CosFileInfo fileInfo = getRep().isExists(entity.getBucketName() , entity.getObjectKey());
        if (fileInfo == null) return false;
        else return true;
    }

    @Override
    public Page<CosFileInfoDto> pageByFileNameLike(FileNamePageCmd cmd) {
        //构建参数，前后模糊查询
        PageRequest page = PageRequest.of(cmd.getPageNum() -1 , cmd.getPageSize());
        String likeParame = "%" + (cmd.getObjectKey() == null ? "" : cmd.getObjectKey()) + "%";

        if (likeParame.equals("%%")){
            return getRep().findDtos(page);
        }else{
            return getRep().findByObjectKeyLike(likeParame, page);
        }
    }


    @Override
    public <R extends DTO> R convert2DtoSingle(CosFileInfo orginInfo) {
        R fileInfoDto = (R) new CosFileInfoDto();
        BeanUtils.copyProperties(orginInfo,fileInfoDto);
        return fileInfoDto;
    }
}
